package generator;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;

import java.io.File;
import java.util.Map;

public class EnhanceFreemarkerTemplateEngine extends FreemarkerTemplateEngine {
    @Override
    protected void outputCustomFile(Map<String, String> customFile, TableInfo tableInfo, Map<String, Object> objectMap) {

        // 可以调用 tableInfo 的getFieldNames方法获得所有的列
        this.printTableColumn(tableInfo);

        // objectMap 里的key可以在ftl文件中直接引用
        // https://copyfuture.com/blogs-details/20210404114118659h
        String entityName = tableInfo.getEntityName();
        String lowerEntityName = firstLetterToLowerCase(entityName);
        // 获取第一个键
        String firstKey = customFile.keySet().iterator().next();
        System.out.println("firstKey:"+firstKey);
        String otherPath = System.getProperty("user.dir") + "\\"+firstKey+"\\src\\main\\java\\tbs\\imt\\data\\model";
        customFile.forEach((key, value) -> {
            if (!key.contains(".java")){
                return;
            }
            // 拼接路径
            String[] split = key.split("-");
            String fileName = String.format(otherPath + File.separator + split[0] + File.separator + lowerEntityName + File.separator + entityName + "%s", split[1]);
            System.out.println(fileName);
            this.outputFile(new File(fileName), objectMap, value);
        });
    }

    /**
     * 获得所有的表列名
     *
     * @param tableInfo 表信息
     */
    private void printTableColumn(TableInfo tableInfo) {
        System.out.println("所有的列名：" + tableInfo.getFieldNames());
    }

    public static String firstLetterToLowerCase(String str) {
        if (str == null || str.isEmpty()) {
            return str; // 返回原值或根据需求调整
        }

        char firstChar = Character.toLowerCase(str.charAt(0));
        return firstChar + str.substring(1);
    }
}
